﻿using System;
using System.Collections.Generic;
using System.Linq;
using AudioStudio.Components;
using Cinemachine;
using ImageEffects;
using LogSystem;
using UnityEditor;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Video;
using XLua;
using Yoozoo.HRP.Runtime;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Yoozoo.Core.Timeline
{
    public class TimelineConstructor : MonoBehaviour
    {
        public Action<TimelineConstructor> OnConstructComplete;

        [DisplayOnly]
        public string tLineName;
        [DisplayOnly]
        public PlayableDirector playableDirector;
        [DisplayOnly]
        public Camera tLineCamera;
        [DisplayOnly]
        public HCamera tHCamera;
        [DisplayOnly] 
        public AudioListener audioListener;
        [DisplayOnly]
        public CinemachineBrain cinemachineBrain;
        [DisplayOnly]
        public List<TLineObjectAvatar> avatars;
        [DisplayOnly]
        public List<TLineAnimator> animators;
        [DisplayOnly]
        public List<EffectSound> effectSounds;
        [DisplayOnly] 
        public List<CinemachineVirtualCamera> virtualCameras;

        [DisplayOnly] public List<VideoPlayer> mediaPlayers;
        [DisplayOnly] 
        public SetCube setCube;
        [DisplayOnly]
        public bool buildComplete;
        [DisplayOnly]
        public int buildIndex;
        [DisplayOnly]
        public int totalCount;

        public ResLoader resLoader;

        [DisplayOnly]
        public bool editorMode;

        [NonSerialized]
        public bool pausing;

        public string tLinePath;
        
        private void Awake()
        {
            if (editorMode)
            {
                return;
            }
            
            if (avatars == null) avatars = new List<TLineObjectAvatar>();
            if (animators == null) animators = new List<TLineAnimator>();

// #if UNITY_EDITOR
//             foreach (var avatar in avatars)
//             {
//                 if (avatar && avatar.transform.childCount > 0)
//                 {
//                     EditorUtility.DisplayDialog("错误", $"Timeline:{tLineName} 播放失败，TLineObjectAvatar: {avatar.transform.name} 下有子物体，请确保退出了编辑模式~", "-_-");
//                     playableDirector.Stop();
//                     return;
//                 }
//             }
// #endif
            
            buildComplete = false;
            buildIndex = 0;
            totalCount = avatars.Count + animators.Count;

            TimelineConstructorMgr.GetInstance("TimelineConstructorMgr").AddConstructor(this);
        }

        public void OnUpdate()
        {
            if (buildComplete) return;
            
            if (buildIndex >= totalCount)
            {
                buildComplete = true;
                enabled = false;
                OnConstructComplete?.Invoke(this);
                Debug.Log(LogModule.Guide,$"{transform.name} Timeline构建完成");
                return;
            }

            if (buildIndex < avatars.Count)
            {
                avatars[buildIndex].Build();

//#if UNITY_EDITOR
                if (avatars[buildIndex].instance)
                {
                    var es = avatars[buildIndex].instance.GetComponentsInChildren<EffectSound>();
                    foreach (var sound in es)
                    {
                        if (sound)
                        {
                            if (effectSounds == null)
                            {
                                effectSounds = new List<EffectSound>(10);
                            }
                            effectSounds.Add(sound);
                            if (sound.enabled)
                            {
                                UnityEngine.Debug.LogError($"错误~ 实例出来的物体有EffectSound，请保证其默认为关闭状态 ：{sound.transform.name} ");
#if UNITY_EDITOR
                                EditorUtility.DisplayDialog("错误",
                                    $"错误~ 实例出来的物体有EffectSound，请保证其默认为关闭状态 ：{sound.transform.name} ", "OK");
#endif
                            }
                            sound.enabled = false;
                        }
                    }
                }
//#endif
            }
            else
            {
                animators[buildIndex - avatars.Count]?.Build();
            }
            buildIndex++;
        }

        public void OnRemoved()
        {
            if (mediaPlayers != null)
            {
                for (int i = 0; i < mediaPlayers.Count; i++)
                {
                    var mediaPlayer = mediaPlayers[i];
                    if (mediaPlayer)
                    {
                        mediaPlayer.gameObject.SetActive(false);
                        mediaPlayer.Stop();
                    }
                }
            }
        }

        public void Ban()
        {
            if (cinemachineBrain)
            {
                cinemachineBrain.enabled = false;
            }
        }

#if UNITY_EDITOR
        [BlackList]
        public void DestroyErrorComponents(bool refresh = true)
        {
            var audioListener3d = GetComponentInChildren<AudioListener3D>();
            if (audioListener3d)
            { 
                DestroyImmediate(audioListener3d,true);
                UnityEngine.Debug.LogError("Timeline中不能使用AudioListener3d 被自动删除！！！");
            }

            if (!refresh)
            {
                return;
            }

            SavePrefab();
        }
        
        [BlackList]
        public void FindObjectAvatar(bool ed)
        {
            tLineName = transform.name;
            playableDirector = GetComponentInChildren<PlayableDirector>(true);
            cinemachineBrain = GetComponentInChildren<CinemachineBrain>(true);
            tLineCamera = GetComponentInChildren<Camera>(true);
            tHCamera = GetComponentInChildren<HCamera>(true);
            effectSounds = GetComponentsInChildren<EffectSound>(true).ToList();
            virtualCameras = GetComponentsInChildren<CinemachineVirtualCamera>(true).ToList();
            mediaPlayers = GetComponentsInChildren<VideoPlayer>(true).ToList();

            if (virtualCameras!=null)
            {
                foreach (var virtualCamera in virtualCameras)
                {
                    virtualCamera.enabled = false;
                }
            }
            
            if (effectSounds!=null)
            {
                foreach (var sound in effectSounds)
                {
                    sound.enabled = false;
                }
            }
            
            if (tHCamera)
            {
                tHCamera.enabled = false;
            }

            if (tLineCamera)
            {
                tLineCamera.enabled = false;
            }
            
            if (cinemachineBrain)
            {
                cinemachineBrain.enabled = false;
            }
            
            avatars = transform.GetComponentsInChildren<TLineObjectAvatar>(true).ToList();
            
            animators = new List<TLineAnimator>();
            var anims = transform.GetComponentsInChildren<Animator>(true);
            foreach (var anim in anims)
            {
                var tLineAnimator = anim.gameObject.GetOrAddComponent<TLineAnimator>();
                tLineAnimator.animator = anim;
                anim.enabled = false;
                animators.Add(tLineAnimator);
            }

            // if (animators.Count > 30)
            // {
            //     EditorUtility.DisplayDialog("警告", $"这么多Animator，你是认真的吗？ Animator数量：{animators.Count}，最大数量30", "改");
            // }

            var lightElements = GetComponentsInChildren<LightElement>(true);
            foreach (var lightElement in lightElements)
            {
                if (lightElement != null && lightElement.transform != this.transform)
                {
                    lightElement.enabled = false;
                    UnityEngine.Debug.LogError("去除Timeline子物体的LightElement：" + lightElement.name,
                        lightElement.gameObject);
                }
            }
            
            editorMode = ed;

            DestroyErrorComponents(false);

            SavePrefab();

        }
        
        [BlackList]
        public void ShowObjectAvatar()
        {
            FindObjectAvatar(true);
            if (avatars!=null)
            {
                foreach (var objectAvatar in avatars)
                {
                    objectAvatar.Build();
                }
            }

            if (animators!=null)
            {
                foreach (var lineAnimator in animators)
                {
                    lineAnimator.animator.enabled = true;
                }
            }

            if (virtualCameras!=null)
            {
                foreach (var virtualCamera in virtualCameras)
                {
                    virtualCamera.enabled = true;
                }
            }
            
            if (effectSounds!=null)
            {
                foreach (var sound in effectSounds)
                {
                    sound.enabled = true;
                }
            }

            
            if (tLineCamera)
            {
                tLineCamera.enabled = true;
            }

            if (tHCamera)
            {
                tHCamera.enabled = true;
            }

            if (cinemachineBrain)
            {
                cinemachineBrain.enabled = true;
            }

            SavePrefab();
        }
        
        [BlackList]
        public void HideObjectAvatar()
        {

            FindObjectAvatar(false);
            if (avatars!=null)
            {
                foreach (var objectAvatar in avatars)
                {
                    objectAvatar.Hide();
                }
            }
            
            if (animators!=null)
            {
                foreach (var lineAnimator in animators)
                {
                    lineAnimator.animator.enabled = false;
                }
            }
            
            if (virtualCameras!=null)
            {
                foreach (var virtualCamera in virtualCameras)
                {
                    virtualCamera.enabled = false;
                }
            }
            
            if (effectSounds!=null)
            {
                foreach (var sound in effectSounds)
                {
                    sound.enabled = false;
                }
            }
            
            if (tLineCamera)
            {
                tLineCamera.enabled = false;
            }

            if (tHCamera)
            {
                tHCamera.enabled = false;
            }
            
            if (cinemachineBrain)
            {
                cinemachineBrain.enabled = false;
            }

            if (playableDirector)
            {
                playableDirector.time = 0;
            }
            
            SavePrefab();
        }

        private void SavePrefab()
        {
            var stage = UnityEditor.SceneManagement.
                PrefabStageUtility.GetCurrentPrefabStage();
            var prefab = PrefabUtility.GetNearestPrefabInstanceRoot(this.gameObject);
            if (prefab != null)
            {
                if (stage == null)
                {
                    PrefabUtility.ApplyPrefabInstance(prefab, InteractionMode.AutomatedAction);
                    Selection.activeGameObject = gameObject;
                    //EditorSceneManager.SaveScene(SceneManager.GetActiveScene());
                }
                else
                {
                    EditorUtility.SetDirty(prefab);
                }

            }
            else
            {
                if (stage != null)
                    EditorUtility.SetDirty(gameObject);
                else
                    PrefabUtility.SavePrefabAsset(gameObject);
            }
        }
        
#endif

       
    }
}